<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Class Role
 * 角色管理
 */

class Role extends CT_Controller
{

    const OPERATE_LOG_NAME = '权限管理';

    function __construct()
    {
        parent::__construct();
        $this->load->model('role_model');
        $this->load->model("role_action_model");
        $this->load->model("permissions_model");
        $this->lang->load('form_validation', 'chinese');
        $this->load->helper('form');
        $this->load->library('form_validation');

        $this->t = $this->ct_template;
    }


    /**
     * 角色列表
     *
     */
    public function index()
    {
        $page = $this->input->get('per_page') ? intval($this->input->get('per_page')) : 1;
        $pagesize = $this->config->item('per_page')?$this->config->item('per_page'):20;
        $start = ($page-1) * $pagesize;
        $condition = array();
        //获取总数
        $this->role_model->findAll( $condition,null,null,null,null);
        $total =$this->role_model->__numRows;
        $role_all = $this->role_model->findAll( $condition,null,null,$start,$pagesize);
        $pagelink = $this->pagination($total,$pagesize);
        $data['pagelink'] = $pagelink;
        $data['role_all'] = $role_all;
        $data['_title'] ='角色列表';


        $this->t->write('_title', '角色列表');
        $this->t->write('breadcrum', '角色列表');

        $this->t->write_view('content', 'admin/role/index', $data, false);
        $this->t->render();
    }




    /**
     * 角色添加
     */
    function add()
    {
        $data = array( );
        $this->form_validation->set_rules('name', '角色名称', 'required');
        if( $this->form_validation->run() == FALSE ){

        }else{

            $name = $this->input->post('name',TRUE);
            //验证角色名称是否已经存在
            $check_res=$this->role_model->check_role_name($name,NULL);
            if(!empty($check_res))
            {
                $alerts = array('error' => '添加失败，角色名称已存在');
                $this->common_jump_url($alerts);
            }

            $db = $this->db;
            $db->trans_begin();
            $data = array(
                    'name'=>$name,
            );
            $this->role_model->insert($data);
            //记录日志
            $data=array(
                'old_content'=>'',
                'new_content'=>'新增角色“'.$name.'”',
                'action_name'=>self::OPERATE_LOG_NAME
            );
            $this->set_admin_operate_log($data);

            if ($db->trans_status() === FALSE) {
                $db->trans_rollback();
                $alerts = array('error' => '数据库繁忙,角色添加失败 !');
                $this->common_jump_url($alerts);

            }else{

                $db->trans_commit();
                $alerts = array('success' => '角色添加成功');
                $this->common_jump_url($alerts,'/admin/role/');

            }


        }
        $data['_title'] ='添加角色';
        $this->t->write('_title', '角色添加');
        $this->t->write('breadcrum', '角色添加');
        $this->t->write_view('content', 'admin/role/add', $data, false);
        $this->t->render();
    }


    /**
     * 角色编辑
     */
    public  function edit()
    {

        $this->form_validation->set_rules('name', '角色名称', 'required');
        if( $this->form_validation->run() == FALSE ){

        }else{

            $role_id=$this->input->post("id",TRUE);
            $name = $this->input->post('name',TRUE);

            //获取之前的角色
            $row = $this->role_model->find( array('id'=>$role_id));

            //验证角色名称是否存在
            $check_res=$this->role_model->check_role_name($name,$role_id);
            if(!empty($check_res))
            {
                $alerts = array('error' => '修改失败，角色名称已存在');
                $this->common_jump_url($alerts);
            }

            $db = $this->db;
            $db->trans_begin();
            $field = array('name'=>$name);
            $where = array('id'=>$role_id);
            $this->role_model->update($field,$where);
            //记录日志
            $data=array(
                'old_content'=>$row['name'],
                'new_content'=>$name,
                'action_name'=>self::OPERATE_LOG_NAME
            );
            $this->set_admin_operate_log($data);
            if ($db->trans_status() === FALSE) {
                $db->trans_rollback();
                $alerts = array('error' => '数据库繁忙,角色修改失败 ！');
                $this->common_jump_url($alerts);

            }else{

                $db->trans_commit();

                $alerts = array('success' => '角色编辑成功');
                $this->common_jump_url($alerts,'/admin/role/');

            }

        }


        $role_id=$this->input->get("id",TRUE);
        if(empty($role_id))
        {
            $alerts = array('error'=>'参数错误' );
            $this->common_jump_url($alerts);
        }
        $data = array( );
        $row = $this->role_model->find( array('id'=>$role_id));
        $data['role_id']=$role_id;
        $data['name'] = $row['name'];
        $data['_title'] ='编辑角色';
        $this->t->write('_title', '角色编辑');
        $this->t->write('breadcrum', '角色编辑');
        $this->t->write_view('content', 'admin/role/edit', $data, false);
        $this->t->render();
    }



    /**
     * 角色删除
     */

    function role_del()
    {

        $role_id=$this->input->post("role_id",TRUE);

        $role_res=$this->role_model->find(array('id'=>$role_id));
        if($role_res['name']==='超级管理员')
        {
            echo json_encode(array('state'=>'fail','msg'=>'参数有误，角色删除失败!'));
            return false;
        }

        if(!empty($role_id))
        {
            $db = $this->db;
            $db->trans_begin();
            $where = array('id'=>$role_id);
            $this->role_model->delete($where);

            //记录日志
            $data=array(
                'old_content'=>$role_res['name'],
                'new_content'=>'删除角色“'.$role_res['name'].'”',
                'action_name'=>self::OPERATE_LOG_NAME
            );
            $this->set_admin_operate_log($data);

            if ($db->trans_status() === FALSE) {
                $db->trans_rollback();
                echo json_encode(array('state'=>'fail','msg'=>'数据库繁忙,角色删除失败 ！'));
                return false;

            }else{

                $db->trans_commit();
                echo json_encode(array('state'=>'fail','msg'=>'角色删除成功'));
                return false;

            }

        }else{

            echo json_encode(array('state'=>'fail','msg'=>'参数有误，角色删除失败!'));
            return false;

        }
    }


    /**
     * 为角色分配权限
     */
    public  function  set_permissions()
    {
        //获取角色id
        $role_id=$this->input->get_int("id",TRUE);
        //获取所有的权限列表
        $top_permissions_res=$this->permissions_model->get_all_permissions();
        $permission_res=array();
        foreach($top_permissions_res as $key=> $val){

            $permission_res[$val]=$this->permissions_model->get_all_permissions($key);
        }
        //获取已经为该角色分配的权限

        $already_permission_res=$this->role_action_model->findAll(array('rid'=>$role_id));
        //默认赋值为空数组 防止新角色分配权限报错
        $already_permission_arr=array();
        foreach($already_permission_res as $val){
            $already_permission_arr[]=$val["aid"];
        }
        //获取角色名称
        $role_detail=$this->role_model->find(array('id'=>$role_id));
        $data['role_name']=$role_detail['name'];
        $data['role_id'] = $role_id;
        $data['permission_res']=$permission_res;
        $data['already_permission_arr']=$already_permission_arr;

        $this->t->write('_title', '为角色分配权限');
        $this->t->write('breadcrum', '分配权限');
        $this->t->write_view('content', 'admin/role/set', $data, false);
        $this->t->render();

    }



    /**
     * 权限分配的入库操作
     */
    public function do_add_permissions()
    {

        $role_id=$this->input->post("role_id",TRUE);
        $role_detail=$this->role_model->find(array('id'=>$role_id));

        //获取已经为该角色分配的权限
        $already_permission_res=$this->role_action_model->findAll(array('rid'=>$role_id),'aid');
        //转为一维数组
        $already_permission_res=$this->two2one($already_permission_res);
        //转化为写入日志表需要的格式
        $old_log_content=$this->get_permissions_log_content($already_permission_res);
        //转化为最终的写入日志的形式
        $old_log_content=$this->get_real_log_content($old_log_content);

        $permissions=$this->input->post("permissions",TRUE);
        if(empty($permissions) || !is_array($permissions))
        {

            $alerts = array('error' => '请至少选择一项操作权限！');
            $this->common_jump_url($alerts);
        }

        //获取新的需要写入日志的内容
        $new_log_content=$this->get_permissions_log_content($permissions);
        //操作后需要写入日志的最终内容
        $new_log_content=$this->get_real_log_content($new_log_content);

        $db = $this->db;
        $db->trans_begin();
        $where = array('rid'=>$role_id);
        $this->role_action_model->delete($where);


        //插入权限表（制作多条插入的数组）
        foreach($permissions as $key=>$val)
        {
            $multi_insert_data[]=array('aid'=>$val,'rid'=>$role_id);
        }

        $this->role_action_model->mutli_insert($multi_insert_data);

        //记录日志
        $data=array(
            'old_content'=>$role_detail['name'].'：<br />'.$old_log_content,
            'new_content'=>$role_detail['name'].'：<br />'.$new_log_content,
            'action_name'=>self::OPERATE_LOG_NAME
        );
        $this->set_admin_operate_log($data);

        if ($db->trans_status() === FALSE) {
            $db->trans_rollback();
            $alerts = array('error' => '数据库繁忙,角色分配权限失败 !');
            $this->common_jump_url($alerts);

        }else{

            $db->trans_commit();
            $alerts = array('success' => '角色分配权限成功');
            $this->common_jump_url($alerts,'/admin/role/');
        }

    }


    /**
     * 记录角色操作、权限操作的日志
     * @param $data
     */
    private  function set_admin_operate_log($data)
    {
        $this->load->model("admin_operate_log_model");

        $field=array(
            'old_content'=>$data['old_content'],
            'new_content'=>$data['new_content'],
            'action_name'=>$data['action_name'],
            'create_time'=>date("Y-m-d H:i:s"),
            'uid'=>$this->_admin_uid

        );
        
        $this->admin_operate_log_model->insert($field);
    }


    /**
     * 根据子级id求解父级权限的名称
     * @param int $child_aid
     */
    private  function get_top_action_name($child_aid=0)
    {
        return $this->permissions_model->get_top_action_name($child_aid);

    }

    /**
     * 获取子级权限的名称
     * @param int $child_aid
     * @return mixed
     */
    private  function get_child_action_name($child_aid=0)
    {

        $child_action=$this->permissions_model->find(array('id'=>$child_aid),'name');
        return $child_action['name'];

    }


    /**
     * 根据子级权限的id集合，获取写入日志的内容形式
     * @param $arr
     * @return array
     */
    private  function get_permissions_log_content($arr)
    {
        $res=array();
        foreach($arr as $val)
        {
            $child_action_name=$this->get_child_action_name($val);
            $top_action_name=$this->get_top_action_name($val);
            $res[$top_action_name][]=$child_action_name;

        }
        return $res;

    }

    private  function two2one($arr)
    {
        $res=array();
        foreach($arr as $val)
        {
            $res[]=$val['aid'];

        }

        return $res;
    }


    /**
     * 获取分配权限最终写入数据库的内容形式
     * @param $arr
     * @return string
     */
    private function  get_real_log_content($arr)
    {
        $str='';
        foreach($arr as $key=>$val)
        {

            $str.=$key.'<'.implode('、',$val).'>'.'<br />';
        }

        return $str;
    }

}
